<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="分支名称" prop="branchName">
          <el-input
            v-model="queryParams.branchName"
            placeholder="请输入分支名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="repositoryId">
          <el-select v-model="queryParams.repositoryId" placeholder="选择仓库" clearable style="width: 200px">
            <el-option 
              v-for="repo in repositories"
              :key="repo.id"
              :label="repo.name"
              :value="repo.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分支类型" prop="branchType">
          <el-select v-model="queryParams.branchType" placeholder="分支类型" clearable style="width: 200px">
            <el-option label="主分支" value="MAIN" />
            <el-option label="开发分支" value="DEVELOP" />
            <el-option label="功能分支" value="FEATURE" />
            <el-option label="修复分支" value="HOTFIX" />
            <el-option label="发布分支" value="RELEASE" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="分支状态" clearable style="width: 200px">
            <el-option label="活跃" value="ACTIVE" />
            <el-option label="已合并" value="MERGED" />
            <el-option label="已删除" value="DELETED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Merge"
            :disabled="single"
            @click="handleMerge"
          >合并</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 分支表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="branchList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="分支名称" align="center" prop="branchName" min-width="150">
          <template #default="scope">
            <div class="branch-name">
              <el-icon class="branch-icon"><Branch /></el-icon>
              <span>{{ scope.row.branchName }}</span>
              <el-tag v-if="scope.row.isDefault" type="success" size="small">默认</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="所属仓库" align="center" prop="repositoryName" width="150" />
        <el-table-column label="分支类型" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getBranchTypeColor(scope.row.branchType)">
              {{ getBranchTypeText(scope.row.branchType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="基于分支" align="center" prop="baseBranch" width="120" />
        <el-table-column label="最新提交" align="center" min-width="200">
          <template #default="scope">
            <div class="commit-info" v-if="scope.row.lastCommit">
              <div class="commit-message">{{ scope.row.lastCommit.message }}</div>
              <div class="commit-meta">
                <span class="commit-hash">{{ scope.row.lastCommit.hash.substring(0, 8) }}</span>
                <span class="commit-author">{{ scope.row.lastCommit.author }}</span>
                <span class="commit-time">{{ formatTime(scope.row.lastCommit.time) }}</span>
              </div>
            </div>
            <span v-else class="no-commit">暂无提交</span>
          </template>
        </el-table-column>
        <el-table-column label="提交数" align="center" prop="commitCount" width="80" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建者" align="center" prop="creatorName" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              icon="View"
              @click="handleView(scope.row)"
              link
            >查看</el-button>
            <el-button
              type="success"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              link
            >修改</el-button>
            <el-button
              v-if="scope.row.status === 'ACTIVE'"
              type="warning"
              icon="Merge"
              @click="handleMerge(scope.row)"
              link
            >合并</el-button>
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              link
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加/编辑分支对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
    >
      <el-form :model="dialog.form" :rules="dialog.rules" ref="dialogFormRef" label-width="100px">
        <el-form-item label="分支名称" prop="branchName">
          <el-input v-model="dialog.form.branchName" placeholder="请输入分支名称" />
        </el-form-item>
        <el-form-item label="所属仓库" prop="repositoryId">
          <el-select v-model="dialog.form.repositoryId" placeholder="请选择仓库" style="width: 100%">
            <el-option 
              v-for="repo in repositories"
              :key="repo.id"
              :label="repo.name"
              :value="repo.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分支类型" prop="branchType">
          <el-select v-model="dialog.form.branchType" placeholder="请选择分支类型" style="width: 100%">
            <el-option label="主分支" value="MAIN" />
            <el-option label="开发分支" value="DEVELOP" />
            <el-option label="功能分支" value="FEATURE" />
            <el-option label="修复分支" value="HOTFIX" />
            <el-option label="发布分支" value="RELEASE" />
          </el-select>
        </el-form-item>
        <el-form-item label="基于分支" prop="baseBranch">
          <el-select v-model="dialog.form.baseBranch" placeholder="请选择基于分支" style="width: 100%">
            <el-option 
              v-for="branch in baseBranches"
              :key="branch.branchName"
              :label="branch.branchName"
              :value="branch.branchName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否默认" prop="isDefault">
          <el-switch v-model="dialog.form.isDefault" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="dialog.form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分支描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="dialog.loading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 合并分支对话框 -->
    <el-dialog
      v-model="mergeDialog.visible"
      title="合并分支"
      width="500px"
    >
      <el-form :model="mergeDialog.form" label-width="100px">
        <el-form-item label="源分支">
          <el-input v-model="mergeDialog.sourceBranch" disabled />
        </el-form-item>
        <el-form-item label="目标分支">
          <el-select v-model="mergeDialog.form.targetBranch" placeholder="请选择目标分支" style="width: 100%">
            <el-option 
              v-for="branch in targetBranches"
              :key="branch.branchName"
              :label="branch.branchName"
              :value="branch.branchName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合并类型">
          <el-radio-group v-model="mergeDialog.form.mergeType">
            <el-radio label="MERGE">普通合并</el-radio>
            <el-radio label="SQUASH">压缩合并</el-radio>
            <el-radio label="REBASE">变基合并</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合并说明">
          <el-input
            v-model="mergeDialog.form.mergeMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入合并说明"
          />
        </el-form-item>
        <el-form-item label="合并后删除">
          <el-switch v-model="mergeDialog.form.deleteAfterMerge" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="mergeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmMerge" :loading="mergeDialog.loading">确定合并</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getBranchPage, 
  getBranchDetail,
  createBranch,
  updateBranch,
  deleteBranch,
  mergeBranch,
  getRepositoryList,
  getBranchList
} from '@/api/version'
import { useRouter } from 'vue-router'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const branchList = ref([])
const repositories = ref([])
const baseBranches = ref([])
const targetBranches = ref([])
const queryFormRef = ref()
const dialogFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  branchName: undefined,
  repositoryId: undefined,
  branchType: undefined,
  status: undefined
})

// 对话框
const dialog = reactive({
  visible: false,
  title: '',
  loading: false,
  form: {
    id: undefined,
    branchName: '',
    repositoryId: undefined,
    branchType: '',
    baseBranch: '',
    isDefault: false,
    description: ''
  },
  rules: {
    branchName: [{ required: true, message: '分支名称不能为空', trigger: 'blur' }],
    repositoryId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
    branchType: [{ required: true, message: '请选择分支类型', trigger: 'change' }]
  }
})

// 合并对话框
const mergeDialog = reactive({
  visible: false,
  loading: false,
  sourceBranch: '',
  branchId: null,
  form: {
    targetBranch: '',
    mergeType: 'MERGE',
    mergeMessage: '',
    deleteAfterMerge: false
  }
})

// 获取分支列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getBranchPage(queryParams)
    if (response.code === 200) {
      branchList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取分支列表失败')
    }
  } catch (error) {
    console.error('获取分支列表失败:', error)
    ElMessage.error('获取分支列表失败')
  } finally {
    loading.value = false
  }
}

// 获取仓库列表
const getRepositories = async () => {
  try {
    const response = await getRepositoryList()
    if (response.code === 200) {
      repositories.value = response.data || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

// 获取基础分支列表
const getBaseBranches = async (repositoryId) => {
  try {
    const response = await getBranchList({ repositoryId })
    if (response.code === 200) {
      baseBranches.value = response.data || []
      targetBranches.value = response.data || []
    }
  } catch (error) {
    console.error('获取分支列表失败:', error)
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.title = '添加分支'
  dialog.visible = true
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  const branchId = row.id || ids.value[0]
  try {
    const response = await getBranchDetail(branchId)
    if (response.code === 200) {
      dialog.form = { ...response.data }
      dialog.title = '修改分支'
      dialog.visible = true
      if (dialog.form.repositoryId) {
        getBaseBranches(dialog.form.repositoryId)
      }
    }
  } catch (error) {
    console.error('获取分支详情失败:', error)
    ElMessage.error('获取分支详情失败')
  }
}

// 查看按钮操作
const handleView = (row) => {
  router.push(`/version/branch/detail/${row.id}`)
}

// 合并按钮操作
const handleMerge = (row) => {
  const branch = row.id ? row : branchList.value.find(item => ids.value.includes(item.id))
  if (!branch) {
    ElMessage.warning('请选择要合并的分支')
    return
  }
  
  mergeDialog.branchId = branch.id
  mergeDialog.sourceBranch = branch.branchName
  mergeDialog.form = {
    targetBranch: '',
    mergeType: 'MERGE',
    mergeMessage: `Merge branch '${branch.branchName}'`,
    deleteAfterMerge: false
  }
  mergeDialog.visible = true
  getBaseBranches(branch.repositoryId)
}

// 删除按钮操作
const handleDelete = (row) => {
  const branchIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除分支编号为"' + branchIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteBranch(branchIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除分支失败:', error)
      ElMessage.error('删除分支失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  dialogFormRef.value?.validate(async (valid) => {
    if (valid) {
      dialog.loading = true
      try {
        if (dialog.form.id) {
          await updateBranch(dialog.form.id, dialog.form)
          ElMessage.success('修改成功')
        } else {
          await createBranch(dialog.form)
          ElMessage.success('新增成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        dialog.loading = false
      }
    }
  })
}

// 确认合并
const confirmMerge = async () => {
  if (!mergeDialog.form.targetBranch) {
    ElMessage.warning('请选择目标分支')
    return
  }
  
  try {
    mergeDialog.loading = true
    await mergeBranch(mergeDialog.branchId, mergeDialog.form)
    ElMessage.success('合并成功')
    mergeDialog.visible = false
    getList()
  } catch (error) {
    console.error('合并失败:', error)
    ElMessage.error('合并失败')
  } finally {
    mergeDialog.loading = false
  }
}

// 重置表单
const resetForm = () => {
  dialog.form = {
    id: undefined,
    branchName: '',
    repositoryId: undefined,
    branchType: '',
    baseBranch: '',
    isDefault: false,
    description: ''
  }
}

// 工具函数
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

const formatTime = (time) => {
  if (!time) return ''
  const now = new Date()
  const date = new Date(time)
  const diff = now - date
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60))
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60))
      return `${minutes}分钟前`
    }
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString()
  }
}

const getBranchTypeColor = (type) => {
  const colorMap = {
    'MAIN': 'danger',
    'DEVELOP': 'primary',
    'FEATURE': 'success',
    'HOTFIX': 'warning',
    'RELEASE': 'info'
  }
  return colorMap[type] || 'info'
}

const getBranchTypeText = (type) => {
  const textMap = {
    'MAIN': '主分支',
    'DEVELOP': '开发分支',
    'FEATURE': '功能分支',
    'HOTFIX': '修复分支',
    'RELEASE': '发布分支'
  }
  return textMap[type] || type
}

const getStatusType = (status) => {
  const typeMap = {
    'ACTIVE': 'success',
    'MERGED': 'info',
    'DELETED': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'ACTIVE': '活跃',
    'MERGED': '已合并',
    'DELETED': '已删除'
  }
  return textMap[status] || status
}

// 页面加载时获取数据
onMounted(() => {
  getList()
  getRepositories()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}

.branch-name {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .branch-icon {
    color: #409eff;
  }
}

.commit-info {
  text-align: left;
  
  .commit-message {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .commit-meta {
    display: flex;
    gap: 8px;
    font-size: 12px;
    color: #909399;
    
    .commit-hash {
      font-family: monospace;
      background-color: #f5f5f5;
      padding: 2px 4px;
      border-radius: 3px;
    }
  }
}

.no-commit {
  color: #909399;
  font-style: italic;
}
</style>
